<template>
  <div>
    <!-- <div class="toptitle">订单管理</div> -->
    <el-row id="order_total">
      <el-col :span="8">
        <div class="order_content">
          <div class="order_total_title">订单总额</div>
          <div class="order_total_info">
            <span class="order_data" v-bind:class="orderMoneyPlusClass">{{
              totalData.orderMoney
            }}</span>
            <span class="order_dw">元</span>
          </div>
          <div class="order_compared">
            <span class="compared_title">昨日同比</span>
            <span class="compared_data" v-bind:class="orderMoneyPlusClass">{{
              orderMoneyPlus
            }}</span>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="order_content">
          <div class="order_total_title">订单数</div>
          <div class="order_total_info">
            <span class="order_data" v-bind:class="orderNumPlusClass">{{
              totalData.orderNum
            }}</span>
            <span class="order_dw"></span>
          </div>
          <div class="order_compared">
            <span class="compared_title">昨日同比</span>
            <span class="compared_data" v-bind:class="orderNumPlusClass">{{
              orderNumPlus
            }}</span>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="order_content">
          <div class="order_total_title">实际成交总额</div>
          <div class="order_total_info">
            <span class="order_data" v-bind:class="realOrderMoneyPlusClass">{{
              totalData.realOrderMoney
            }}</span>
            <span class="order_dw">元</span>
          </div>
          <div class="order_compared">
            <span class="compared_title">昨日同比</span>
            <span
              class="compared_data"
              v-bind:class="realOrderMoneyPlusClass"
              >{{ realOrderMoneyPlus }}</span
            >
          </div>
        </div>
      </el-col>
    </el-row>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @keyup.enter.native="search()"
    >
      <el-form-item label="大区名称：" v-if="isJT">
        <el-input v-model="formInline.theaterName" placeholder></el-input>
      </el-form-item>
      <el-form-item label="营销区域名称：" v-if="isZQ">
        <el-input v-model="formInline.baseName" placeholder></el-input>
      </el-form-item>
      <el-form-item label="门店名称：" v-if="orgType != '4'">
        <el-input v-model="formInline.shopName" placeholder></el-input>
      </el-form-item>
      <el-form-item label="店主姓名：" v-if="orgType != '4'">
        <el-input v-model="formInline.shopOwnerName" placeholder></el-input>
      </el-form-item>
      <el-form-item label="店主电话：" v-if="orgType != '4'">
        <el-input v-model="formInline.shopOwnerTel" placeholder></el-input>
      </el-form-item>
      <el-form-item label="买家姓名：">
        <el-input v-model="formInline.memberName" placeholder></el-input>
      </el-form-item>
      <el-form-item label="买家电话：">
        <el-input v-model="formInline.memberTel" placeholder></el-input>
      </el-form-item>
      <el-form-item label="订单日期：">
        <!--
        <el-date-picker
          v-model="formInline.orderDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        -->
        <el-date-picker
          v-model="formInline.dateRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="search()"
          size="mini"
          icon="el-icon-search"
          >查询</el-button
        >
        <el-button
          type="primary"
          @click="kong()"
          size="mini"
          icon="el-icon-delete"
          >清空</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      :cell-class-name="tableCellClassName"
      @sort-change="sortTable"
      :row-key="getRowKey"
      v-loading="loading"
      :expand-row-keys="expandRowKeys"
      default-expand-all
      border
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="orgName"
        label="销售区域"
        width
        align="left"
      ></el-table-column>
      <el-table-column
        prop="orderNum"
        label="订单数"
        sortable="custom"
        width="180"
        align="right"
      ></el-table-column>
      <el-table-column
        prop="orderAmount"
        label="订单量"
        sortable="custom"
        width="180"
        align="right"
      ></el-table-column>
      <el-table-column
        prop="orderMoney"
        label="订单额"
        sortable="custom"
        width="180"
        align="right"
        :formatter="fixData"
      ></el-table-column>
      <el-table-column
        prop="realOrderMoney"
        label="实际成交额"
        sortable="custom"
        width="180"
        align="right"
        :formatter="fixData"
      ></el-table-column>
      <el-table-column label="明细" width align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="showDialogOrderList(scope.row)"
            >查看订单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--门店订单列表弹窗-->
    <el-dialog title="门店订单" :visible.sync="dialogOrderVisible" width="60%">
      <el-table
        :data="orderData"
        stripe
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        @sort-change="sortTable2"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="订单号">
                <span>{{ props.row.orderNo }}</span>
              </el-form-item>
              <el-form-item label="门店名称">
                <span>{{ props.row.orgName }}</span>
              </el-form-item>
              <el-form-item label="店主姓名">
                <span>{{ props.row.shopOwnerName }}</span>
              </el-form-item>
              <el-form-item label="店主手机号">
                <span>{{ props.row.shopOwnerTel }}</span>
              </el-form-item>
              <el-form-item label="买家名称">
                <span>{{ props.row.memberName }}</span>
              </el-form-item>
              <el-form-item label="买家手机号">
                <span>{{ props.row.tel }}</span>
              </el-form-item>
              <el-form-item label="业务员名称">
                <span>{{ props.row.userName }}</span>
              </el-form-item>
              <el-form-item label="业务员手机号">
                <span>{{ props.row.userTel }}</span>
              </el-form-item>
              <el-form-item label="订单总量">
                <span>{{ props.row.totalAmount | numFilter }}</span>
              </el-form-item>
              <el-form-item label="订单总价">
                <span>{{ props.row.totalMoney | numFilter }}</span>
              </el-form-item>
              <el-form-item label="实收总额">
                <span>{{ props.row.receivedMoney | numFilter }}</span>
              </el-form-item>
              <el-form-item label="配送地址">
                <span>{{ props.row.addressName }}</span>
              </el-form-item>
              <el-form-item label="成交时间">
                <span>{{ props.row.createTime }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          v-if="orderParam.orgType != 4"
          property="orgName"
          label="门店名称"
          sortable="custom"
          width
          align="left"
        ></el-table-column>
        <el-table-column
          property="memberName"
          label="买家名称"
          sortable="custom"
          width
          align="left"
        ></el-table-column>
        <el-table-column
          property="totalAmount"
          label="订单总量"
          sortable="custom"
          width
          align="right"
        ></el-table-column>
        <el-table-column
          property="totalMoney"
          label="订单总价"
          sortable="custom"
          width
          align="right"
          :formatter="fixData"
        ></el-table-column>
        <el-table-column
          property="receivedMoney"
          label="实收总额"
          sortable="custom"
          width
          align="right"
          :formatter="fixData"
        ></el-table-column>
        <el-table-column
          property="createTime"
          label="成交时间"
          sortable="custom"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column label="明细" width align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="showDialogOrderDetail(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-form :inline="true">
        <el-form-item style="margin-top: 16px;"></el-form-item>
      </el-form>
      <div class="block" style="margin-top:-49px">
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
          :current-page="listQuery2.current"
          :page-size="listQuery2.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        ></el-pagination>
      </div>
    </el-dialog>

    <!--门店订单详细弹窗-->
    <el-dialog
      title="订单详细"
      :visible.sync="dialogOrderDetailVisible"
      width="70%"
    >
      <el-table
        :data="productData"
        stripe
        :summary-method="getSummaries"
        show-summary
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          property="goodsName"
          label="商品名称"
          sortable
          width
          align="left"
        ></el-table-column>
        <el-table-column
          property="price"
          label="销售价（元）"
          sortable
          width
          align="right"
          show-overflow-tooltip
          :formatter="fixData"
        ></el-table-column>
        <el-table-column
          property="amount"
          label="数量"
          sortable
          width
          align="right"
          :formatter="fixData"
        ></el-table-column>
        <el-table-column
          property="unitName"
          label="单位"
          sortable
          width
          align="right"
          :formatter="fixData"
        ></el-table-column>
        <el-table-column
          property="money"
          label="商品总价（元）"
          sortable
          width
          align="right"
          :formatter="fixData"
        ></el-table-column>
        <el-table-column
          property="realMoney"
          label="实际成交（元）"
          sortable
          width
          align="right"
          :formatter="fixData"
        ></el-table-column>
      </el-table>
    </el-dialog>
    <!--
    <el-form :inline="true">
      <el-form-item style="margin-top: 6px;">
      </el-form-item>
    </el-form>
    -->
    <!--
    <div class="block" style="margin-top:-49px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
     </div>
    -->
  </div>
</template>

<script>
import {
  queryOrgTotal,
  queryOrgChildList,
  queryOrgOrderList,
  queryOrderGoodsList,
} from '@/api/tradeOrder';

import qs from 'qs';
var curDate = new Date();
var curDateStr = '';
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
month = month > 9 ? month : '0' + month;
var date = curDate.getDate();
date = date > 9 ? date : '0' + date;
curDateStr = year + '-' + month + '-' + date;
export default {
  data() {
    return {
      logininfo: '',
      orgSeq: '',
      orgType: '',
      isInitExpand: false,
      loading: true,
      totalData: {
        orderMoney: 0,
        orderMoneyPlus: 0,
        orderNum: 0,
        orderNumPlus: 0,
        realOrderMoney: 0,
        realOrderMoneyPlus: 0,
      },
      formInline: {
        theaterName: '',
        baseName: '',
        shopName: '',
        shopOwnerName: '',
        shopOwnerTel: '',
        memberName: '',
        memberTel: '',
        orderDate: curDateStr,
        dateRange: [curDateStr, curDateStr],
      },
      expandRowKeys: [],
      tableData: [],
      total: 0,
      listQuery: {
        current: 1,
        size: 100,
      },
      sort: '',
      order: '',
      dialogOrderVisible: false,
      dialogOrderDetailVisible: false,
      orderParam: {
        shopUuid: '',
        shopIds: '',
        orgType: '',
        shopOwnerName: '',
        shopOwnerTel: '',
        memberName: '',
        memberTel: '',
        orderDate: '',
        dateRange: '',
        orderNo: '',
        sort: '',
        order: '',
      },
      orderData: [],
      total2: 0,
      listQuery2: {
        current: 1,
        size: 100,
      },
      productData: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.logininfo = localStorage.getItem('logininfo');
    let orgJson = JSON.parse(this.logininfo);
    if (
      orgJson != null &&
      orgJson.orgList != null &&
      orgJson.orgList.length > 0
    ) {
      this.orgSeq = orgJson.orgList[0].orgSeq;
      this.orgType = orgJson.orgList[0].orgType;
    }
    this.rolemanageone();
  },
  updated() {
    if (!this.isInitExpand) {
      this.expandAll();
    }
  },
  filters: {
    numFilter(value) {
      let realVal = '';
      if (!isNaN(value) && value !== '') {
        // 截取当前数据到小数点后2位
        realVal = parseFloat(value).toFixed(2);
      } else {
        realVal = '--';
      }
      return realVal;
    },
  },
  methods: {
    getRowKey(row) {
      return row.orgSeq;
    },
    /*第一层表格*/
    rolemanageone() {
      let data = {
        orgSeq: this.orgSeq,
        orgType: this.orgType,
        theaterName: this.formInline.theaterName,
        baseName: this.formInline.baseName,
        shopName: this.formInline.shopName,
        shopOwnerName: this.formInline.shopOwnerName,
        shopOwnerTel: this.formInline.shopOwnerTel,
        memberName: this.formInline.memberName,
        memberTel: this.formInline.memberTel,
        orderDate: this.formInline.orderDate,
        dateRange: this.formInline.dateRange.join(),
        sort: this.sort,
        order: this.order,
      };
      queryOrgTotal(data).then((res) => {
        this.loading = false;
        this.tableData = res.result.children;
        this.totalData = {
          orderMoney: res.result.orderMoney.toFixed(2),
          orderMoneyPlus: res.result.orderMoneyPlus.toFixed(2),
          orderNum: res.result.orderNum,
          orderNumPlus: res.result.orderNumPlus,
          realOrderMoney: res.result.realOrderMoney.toFixed(2),
          realOrderMoneyPlus: res.result.realOrderMoneyPlus.toFixed(2),
        };
      });
    },
    expandAll() {
      const els = document.getElementsByClassName('el-table__expand-icon');
      if (els.length > 0) {
        for (let i = 0; i < els.length; i++) {
          els[i].click();
        }
        this.isInitExpand = true;
      }
    },
    search() {
      this.isInitExpand = false;
      this.listQuery.current = 1;
      this.rolemanageone();
    },
    //清空
    kong() {
      this.formInline.theaterName = '';
      this.formInline.baseName = '';
      this.formInline.shopName = '';
      this.formInline.shopOwnerName = '';
      this.formInline.shopOwnerTel = '';
      this.formInline.memberName = '';
      this.formInline.memberTel = '';
    },
    load(tree, treeNode, resolve) {
      if (this.orgType == null || this.orgType == '') {
        this.orgType = 1;
      }
      let nodeOrgType = parseInt(this.orgType) + parseInt(treeNode.level);
      let data = {
        orgSeq: treeNode.rowKey,
        orgType: nodeOrgType,
        theaterName: this.formInline.theaterName,
        baseName: this.formInline.baseName,
        shopName: this.formInline.shopName,
        shopOwnerName: this.formInline.shopOwnerName,
        shopOwnerTel: this.formInline.shopOwnerTel,
        memberName: this.formInline.memberName,
        memberTel: this.formInline.memberTel,
        orderDate: this.formInline.orderDate,
        dateRange: this.formInline.dateRange.join(),
        sort: this.sort,
        order: this.order,
      };
      queryOrgChildList(data).then((res) => {
        resolve(res.records);
      });
    },
    sortTable({ column, prop, order }) {
      this.isInitExpand = false;
      this.sort = prop;
      this.order = order;
      this.rolemanageone();
    },
    handleSizeChange(val) {
      this.isInitExpand = false;
      this.listQuery.size = val;
      this.rolemanageone();
    },
    handleCurrentChange(val) {
      this.isInitExpand = false;
      this.listQuery.current = val;
      this.rolemanageone();
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 &&
        (row.orgType == 1 || row.orgType == this.orgType)
      ) {
        return 'theaterTitleStyle';
      } else {
        return '';
      }
    },
    clickTableRow(row, column, event) {
      this.totalData = {
        orderMoney: row.orderMoney,
        orderMoneyPlus: row.orderMoneyPlus,
        orderNum: row.orderNum,
        orderNumPlus: row.orderNumPlus,
        realOrderMoney: row.realOrderMoney,
        realOrderMoneyPlus: row.realOrderMoneyPlus,
      };
    },
    /*第二层表格*/
    showDialogOrderList(v) {
      this.orderData = [];
      this.orderParam.shopIds = v.shopIds;
      this.orderParam.orgType = v.orgType;
      this.orderParam.shopOwnerName = this.formInline.shopOwnerName;
      this.orderParam.shopOwnerTel = this.formInline.shopOwnerTel;
      this.orderParam.memberName = this.formInline.memberName;
      this.orderParam.memberTel = this.formInline.memberTel;
      this.orderParam.orderDate = this.formInline.orderDate;
      this.orderParam.dateRange = this.formInline.dateRange.join();
      this.listQuery2.current = 1;
      this.getOrderList();
      this.dialogOrderVisible = true;
    },
    getOrderList() {
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: this.orderParam,
      };
      queryOrgOrderList(data).then((res) => {
        this.total2 = res.total;
        this.orderData = res.records;
      });
    },
    sortTable2({ column, prop, order }) {
      this.orderParam.sort = prop;
      this.orderParam.order = order;
      this.listQuery2.current = 1;
      this.getOrderList();
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.getOrderList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.getOrderList();
    },
    /*第三层表格*/
    showDialogOrderDetail(v) {
      this.orderParam.orderNo = v.uuid;
      this.getOrderDetail();
      this.dialogOrderDetailVisible = true;
    },
    getOrderDetail() {
      queryOrderGoodsList(this.orderParam).then((res) => {
        this.productData = res.records;
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if (index === 1 || index === 3) {
          sums[index] = '';
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += '';
        } else {
          sums[index] = '';
        }
        if (!isNaN(sums[index])) {
          sums[index] = parseFloat(sums[index]).toFixed(2);
        }
      });
      return sums;
    },
    fixData(row, column, cellValue, index) {
      if (cellValue != null && !isNaN(cellValue)) {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },
  },
  //其他
  computed: {
    isJT: function() {
      if (this.orgType == '' || this.orgType == '1') {
        return true;
      } else {
        return false;
      }
    },
    isZQ: function() {
      if (this.orgType == '' || this.orgType == '1' || this.orgType == '2') {
        return true;
      } else {
        return false;
      }
    },
    orderMoneyPlusClass: function() {
      return {
        base: true,
        'text-red': this.totalData.orderMoneyPlus > 0,
        'text-green': this.totalData.orderMoneyPlus < 0,
      };
    },
    orderNumPlusClass: function() {
      return {
        base: true,
        'text-red': this.totalData.orderNumPlus > 0,
        'text-green': this.totalData.orderNumPlus < 0,
      };
    },
    realOrderMoneyPlusClass: function() {
      return {
        base: true,
        'text-red': this.totalData.realOrderMoneyPlus > 0,
        'text-green': this.totalData.realOrderMoneyPlus < 0,
      };
    },
    orderMoneyPlus: function() {
      if (this.totalData.orderMoneyPlus >= 0) {
        return '+' + this.totalData.orderMoneyPlus;
      } else {
        return this.totalData.orderMoneyPlus;
      }
    },
    orderNumPlus: function() {
      if (this.totalData.orderNumPlus >= 0) {
        return '+' + this.totalData.orderNumPlus;
      } else {
        return this.totalData.orderNumPlus;
      }
    },
    realOrderMoneyPlus: function() {
      if (this.totalData.realOrderMoneyPlus >= 0) {
        return '+' + this.totalData.realOrderMoneyPlus;
      } else {
        return this.totalData.realOrderMoneyPlus;
      }
    },
  },
};
</script>
<style scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.order_content {
  width: 350px;
  padding: 20px 0;
  margin: 0 auto;
  text-align: center;
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.order_content .order_total_title {
  color: #000;
}
.order_content .order_total_info {
  margin: 10px 0;
}
.order_content .order_data {
  font-size: 1.4em;
  font-weight: bold;
}
.order_content .compared_title {
  font-size: 0.8em;
  color: #999;
}
.text-red {
  color: red;
}
.text-green {
  color: green;
}
.theaterTitleStyle {
  color: #409eff;
  font-weight: bold;
}
.demo-table-expand {
  line-height: 40px;
}
.demo-table-expand label {
  width: 100px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 49%;
}
</style>
